<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Abase_Asearch extends Controller {

    public function before() {
        parent::before();

        if (!Cookie::get('admin', null) || !$this->request->is_ajax()) die('Access denied');
    }

    public function params() {
        return Model::factory($this->request->post('model'))->params();
    }

    public function dataListDefaults() {
        return array(
            'controller' => $this->request->post('model'),
            'baseUrl' => URL::base()
        );
    }

    public function action_search() {
        $params = $this->params();

        $data = DB::select('id', $params['waymark'])
        ->from($params['table'])
        ->where($this->request->post('search_in'), 'like', '%'.$this->request->param('query').'%')
        ->order_by('id', 'DESC')
        ->as_object()
        ->execute();

        $count = count($data);

        $res = View::factory('apieces/abase/searchResults', array(
            'defaults' => $this->dataListDefaults(),
            'data' => $data,
            'waymark' => $params['waymark'],
        ))->render();

        echo json_encode(array('status' => 'ok', 'data' => $res, 'count' => $count.' '.Model::factory('Afunctions')->howMany($count, 'запись', 'записи', 'записей')));
    }

}